import request from '../../utils/request.js'
let isSend =false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    playHoderContent:'',
    hostList:[],
    searchList:[],
    searchContent:'',
    historyList:[]

  },

  handleToSongDetail(event){
    let musicId = event.currentTarget.id;
    wx.navigateTo({
      url: '/pages/songDetail/songDetail?musicId='+musicId,
    })
  },

//删除历史记录
  deleteHistory(){

    wx.showModal({
      content: '确认删除吗？',
      success: (res)=>{
        this.setData({
          historyList: []
        })

        wx.removeStorageSync('historyList');
      }
    })
   
  },
  cancel(){
    this.setData({
      searchList:[],
      searchContent: ''
    })
  },
//input改变触发
  handleInputChange(event){
   let keyWord = event.detail.value;
   this.setData({
     searchContent: keyWord.trim()
   })
   if(isSend){
     return;
   }
   isSend =true;


   this.getSearchList(keyWord);
  
  setTimeout(()=>{
    isSend = false;
  },1000);


  },

  //异步发请求
  async getSearchList(){
   let keyWord =  this.data.searchContent;
   if(!keyWord){
     this.setData({
       searchList:[]
     });

     return;
   }

   let {historyList,searchContent} = this.data;
    let searchList =await request("/search",{keywords:keyWord,limit:10});

    this.setData({
      searchList: searchList.result.songs
    });


//检验是否有此记录
    if(historyList){
      for(let i =0;i<historyList.length;i++){
        console.log(i,"----",historyList[i]);
          if (searchContent.indexOf(historyList[i])!=-1){
            historyList.splice(i,1);
          }
      }
    }
    historyList.unshift(searchContent);

//更新history
    this.setData({
      historyList
    })

    wx.setStorageSync("historyList", historyList);
  },

    //获取数据
async getInitKeyWord(){
  let data = await request("/search/default");
  let hostList = await request("/search/hot/detail");

  this.setData({
    playHoderContent: data.data.showKeyword,
    hostList: hostList.data 
  })

},

//获取历史数据
getHistoryList(){
 let historyList = wx.getStorageSync("historyList");
 if(historyList){
   this.setData({
     historyList
   })
 }
},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取历史数据
    this.getHistoryList();

    this.getInitKeyWord();
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})